<?php


namespace app\common\model;

use app\common\lib\ZhyxMongo;
use app\common\utils\Questions;
use catcher\exceptions\FailedException;
use MongoDB\BSON\ObjectId;
use MongoDB\Client;
use MongoDB\Driver\Manager;
use think\facade\Db;

class QuestionDetail extends BaseModel
{

    protected $name = "question_detail";

    public function saveQuestions($survey, string $id, $session): bool
    {

        $connection = ZhyxMongo::getInstance()->setCollection("question_detail");

        if (is_string($survey)) {
            try {
                $survey = json_decode($survey, true, 512, JSON_THROW_ON_ERROR);
            } catch (\JsonException $e) {
                throw new FailedException("无法解析您的json数据");
            }
        }
        $questions = [];
        foreach ($survey["widgetList"] as $k => $widget) {
            $options = $widget["options"];
            $questions[] = [
                "title" => $options["label"] ?? '',
                "type" => $widget["type"] ?? '',
                "projectId" => $id,
                "question_id" => $options["name"] ?? '',
                'created_at' => time(),
                'updated_at' => time(),
                'deleted_at' => 0,
                'chart_type' => Questions::getChartTypeByDom($widget["type"] ?? "input")
            ];
        }
        $ids = [];

        foreach ($questions as $k => $v) {
            //判断问题是否已经存在
            //$isExists = $this->where([["projectId", "=", $id], ["question_id", "=", $v["question_id"]]])->find();
            $isExists = $connection->findOne(["projectId" => $id, "question_id" => $v["question_id"]], ['session' => $session]);
            if ($isExists) {
                $questionOid = $isExists["_id"];
                $ids[] = $questionOid;
                $connection->updateOne(["_id" => $questionOid], ['$set' => $v], ['session' => $session]);
            } else {
                $result = $connection->insertOne($v, ['session' => $session]);
                $ids[] = (object)$result->getInsertedId();
            }
        }
        //删除剩余的问题
        $connection->updateMany(["projectId" => $id, "_id" => ['$nin' => $ids]], ['$set' => ["deleted_at" => time()]], ['session' => $session]);
        return true;

    }

    public function getLists()
    {
        return $this->mongoSearch()->order(["id" => 1])->select();

    }


}